package com.coolingme.trycatch;

/**
 * 在 try 语句中越是最后使用的资源，越是最早被关闭。
 *
 * @author wangyue
 * @date 2020/12/3 10:32
 */
public class TryCatch3 {
    public static void main(String[] args) {
        /*
        最终输出为：
        do something
        do other things
        other resource is closed
        some resource is closed
         */
        try (ResourceSome some = new ResourceSome();
             ResourceOther other = new ResourceOther()) {
            some.doSome();
            other.doOther();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

class ResourceSome implements AutoCloseable {
    void doSome() {
        System.out.println("do something");
    }

    @Override
    public void close() throws Exception {
        System.out.println("some resource is closed");
    }
}

class ResourceOther implements AutoCloseable {
    void doOther() {
        System.out.println("do other things");
    }

    @Override
    public void close() throws Exception {
        System.out.println("other resource is closed");
    }
}